package com.tianshi.agriculture.adapter;

import android.Manifest;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.pm.PackageManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.tianshi.agriculture.BluetoothScanActivity;
import com.tianshi.agriculture.R;

import java.util.ArrayList;
import java.util.List;

//import com.tianshi.agriculture.fragment.TabsFragment;

public class BluetoothDeviceAdapter extends BaseAdapter {
	private List<BluetoothDevice> bluetoothDevices = new ArrayList<BluetoothDevice>();
	private Context mContext;
	private int REQUEST_CODE = 100;

	public BluetoothDeviceAdapter(Context context, List<BluetoothDevice> bluetoothDevices) {
		mContext = context;
		this.bluetoothDevices = bluetoothDevices;
	}

	@Override
	public int getCount() {
		return bluetoothDevices.size();
	}

	@Override
	public Object getItem(int i) {
		return null;
	}

	@Override
	public long getItemId(int i) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup viewGroup) {
		BaseViewHolder holder = BaseViewHolder.
				getViewHolder(mContext, convertView, viewGroup, R.layout.item_device_list, position);
		TextView name = holder.getView(R.id.mDeviceName);
		TextView address = holder.getView(R.id.mDeviceMacAddress);
		if (ActivityCompat.checkSelfPermission(this.mContext, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
			// TODO: Consider calling
			//    ActivityCompat#requestPermissions
			// here to request the missing permissions, and then overriding
			//   public void onRequestPermissionsResult(int requestCode, String[] permissions,
			//                                          int[] grantResults)
			// to handle the case where the user grants the permission. See the documentation
			// for ActivityCompat#requestPermissions for more details.
			if (ContextCompat.checkSelfPermission(this.mContext, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
				ActivityCompat.requestPermissions((AppCompatActivity)this.mContext, new String[]{Manifest.permission.BLUETOOTH_CONNECT}, REQUEST_CODE);
			}
		}

		name.setText(bluetoothDevices.get(position).getName());
		address.setText(bluetoothDevices.get(position).getAddress());
		return holder.getConvertView();
	}

	public void updateView() {
		notifyDataSetChanged();
	}
}
